package com.cipe.cmrs.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class SessionObjectFilter extends OncePerRequestFilter {
    public static final String UNSAVED_PAYMENT = "unsavedPaymentrequest";
    public static final String UNSAVED_PARTNER_GRANT = "unsavedPartnerGrant";
    private static String[] paymentSessionObjectUrls = new String[]{ "showAddPaymentrequest.do", "showEditPaymentrequest.do",
        "processPaymentrequest.do", "showAddPayee.do", "showEditPayeeBankInfo.do", "showEditPayeePersonalInfo.do", "savePayee.do" };
    private static String[] grantSessionObjectUrls = new String[]{ "showAddPartnergrant.do", "showAddPartner.do",
        "showEditPartnergrantView.do" };

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        String acceptType = request.getHeader("Accept");
        // Ignore json and get requests
        if ("GET".equalsIgnoreCase(request.getMethod()) && !acceptType.toUpperCase().contains("JSON")) {
            checkPaymentSessionObject(request);
            checkGrantSessionObject(request);
        }
        filterChain.doFilter(request, response);
    }

    private void checkPaymentSessionObject(HttpServletRequest request) {
        boolean isPaymentUrl = false;
        String url = request.getRequestURL().toString();
        for (String u : paymentSessionObjectUrls) {
            if (url.contains(u)) {
                isPaymentUrl = true;
                break;
            }
        }

        if (!isPaymentUrl) {
            request.getSession().removeAttribute(UNSAVED_PAYMENT);
        }
    }

    private void checkGrantSessionObject(HttpServletRequest request) {
        boolean isGrantUrl = false;
        String url = request.getRequestURL().toString();
        for (String u : grantSessionObjectUrls) {
            if (url.contains(u)) {
                isGrantUrl = true;
                break;
            }
        }

        if (!isGrantUrl) {
            request.getSession().removeAttribute(UNSAVED_PARTNER_GRANT);
        }
    }
}
